package com.uzai.console.web.tb.tbtokennew;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.taobao.api.internal.util.WebUtils;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.tb.tbtokennew.TbTokenNewCallBackDto;
import com.uzai.console.entity.TbTokenNew;
import com.uzai.console.mapper.TbTokenNewMapper;
import com.uzai.console.service.tb.tbtokennew.TbTokenNewCallBackService;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jianghan
 * @date 2019-06-17 11:39
 */
@Api(value = "新淘宝回调函数",tags = "新淘宝|新淘宝联盟", hidden = true)
@ApiSort(9)
@RestController
public class TbTokenNewCallbackController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger(TbTokenNewCallbackController.class);

    @Autowired
    private TbTokenNewMapper tbTokenNewMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private TbTokenNewCallBackService tbTokenNewCallBackService;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 回调获取授权
     * @param code
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新淘宝联盟刷新授权回调函数", hidden = true)
    @GetMapping("/tb/callback/new")
    public void callback(String code, String state) throws Exception {
        logger.info("code:{},state:{}",new Object[]{code,state});

        String url="https://oauth.taobao.com/token";
        Map<String, String> props = new HashMap<>();
        props.put("grant_type", "authorization_code");
        props.put("code", code);
        props.put("client_id", uzaiConsoleSysConfig.getTbTokenNewAppkey());
        props.put("client_secret", uzaiConsoleSysConfig.getTbTokenNewAppsecret());
        props.put("redirect_uri", uzaiConsoleSysConfig.getTbTokenCallback());
        props.put("view","web");
        String result;
        try{
            logger.info("tb token params:{}",props);
            result = WebUtils.doPost(url, props, 30000, 30000);
            logger.info("tb token callback:{}",result);
            Map<String,Object> tokenVo = JSONObject.parseObject(result, Map.class);
            if (tokenVo.get("error")!=null){
                getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=0&msg="+ URLEncoder.encode(tokenVo.get("error").toString(),"UTF-8"));
            }

            TbTokenNew tbTokenNew = new TbTokenNew();
            int now = DateUtil.getNowTime();
            tbTokenNew.setId(IdWorker.getId());

            //state 为merId_type拼凑的参数
            if(StringUtils.isNotBlank(state)){
                String[] stateArr = state.split("_");
                if(stateArr != null && stateArr.length == 2){
                    //merId
                    tbTokenNew.setMerId(Long.parseLong(stateArr[0]));
                    //类型
                    tbTokenNew.setType(Integer.parseInt(stateArr[1]));
                }
            }
            tbTokenNew.setUserName(URLDecoder.decode(tokenVo.get("taobao_user_nick").toString(),"UTF-8"));
            tbTokenNew.setUserId(Long.valueOf(tokenVo.get("taobao_user_id").toString()));
            tbTokenNew.setAccessToken(tokenVo.get("access_token").toString());
            tbTokenNew.setRefreshToken(tokenVo.get("refresh_token").toString());
            tbTokenNew.setExpiresin(Integer.parseInt(tokenVo.get("expires_in").toString()));
            tbTokenNew.setReExpiresin(Integer.parseInt(tokenVo.get("re_expires_in").toString()));
            tbTokenNew.setAuthTime(now);
            tbTokenNew.setCreateTime(now);
            tbTokenNew.setUpdateTime(now);
            tbTokenNew.setExptime(now+tbTokenNew.getExpiresin());
            //调用token保存方法
            tbTokenNewCallBackService.add(tbTokenNew);

            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=1");

        }catch(Exception e){
            logger.error("callback err:{}",e);
            getResponse().sendRedirect(uzaiConsoleSysConfig.getTokenAuthReturnUrl() + "?state=0&msg="+ URLEncoder.encode(e.getMessage(),"UTF-8"));
        }
    }

    /**
     * 回调获取授权(2.0调用接口）
     * @param
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新淘宝联盟刷新授权回调函数(2.0系统调用）")
    @PostMapping("/tb/oauth/new")
    public Object tbOauth(@RequestBody TbTokenNewCallBackDto tbTokenNewCallBackDto) {
        tbTokenNewCallBackService.oauth(tbTokenNewCallBackDto);
        return true;
    }

}
